<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\SoftDeletes;

class goodsModel extends Model
{
    use SoftDeletes;
    use \app\traits\goodsactivity;

    protected $table = 'goods';
    protected $primaryKey = 'id';
    protected $appends = [
        'dispatch_type_arr',
        'parent_category_id',
    ];

    protected static function booted()
    {
        //限定查询自营全局作用域
        static::addGlobalScope('dianpu_id', function (Illuminate\Database\Eloquent\Builder $builder) {
            $builder->where('dianpu_id', '=', 0);
        });
    }

    protected function serializeDate($date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getDispatchTypeArrAttribute($value)
    {
        return array_filter(explode(',', $this->dispatch_type));
    }

    public function getParentCategoryIdAttribute($value)
    {
        $catId = explode(',', $this->category_ids)[0];
        if (!$catId) return '';
        return $this->getParentId($catId);
    }

    private function getParentId($catId)
    {
        $pid = categoryModel::where('id', $catId)->value('pid');
        if ($pid === 1 || !$pid) {
            return (int) $catId;
        } else {
            return $this->getParentId($pid);
        }
    }

    public function skuPrice()
    {
        return $this->hasMany(goodsskupriceModel::class, 'goods_id', 'id')->orderBy('id');
    }

    public function getImagesAttribute($value)
    {
        return explode(',', $value);
    }

    public function getParamsAttribute()
    {
        return $this->attributes['params'] ? json_decode($this->attributes['params']) : [];
    }

    public function getAutoshowStartTextAttribute()
    {
        if ($this->attributes['autoshow_start'] == -1) {
            return 'notend';
        } else {
            return timestamp($this->attributes['autoshow_start']?:mktime(0,0,0,date('m'),date('d')+1,date('Y')));
        }
    }

    public function getAutoshowEndTextAttribute()
    {
        if ($this->attributes['autoshow_end'] == -1) {
            return 'notend';
        } else {
            return timestamp($this->attributes['autoshow_end']?:mktime(0,0,0,date('m'),date('d')+2,date('Y'))-1);
        }
    }

    public function stock()
    {
        return goodsskupriceModel::where('goods_id', $this->attributes['id'])->sum('stock');
    }

    public function getGoodsPackageInfo()
    {
        return $this->hasOne(\app\modules\Admin\models\goodspackageModel::class, 'goods_id', 'id');
    }

    // 获取秒杀商品列表
    public static function getSeckillGoodsList($params)
    {
        $type = $params['type'] ?? 'all';

        if ((new self)->hasRedis()) {
            // 如果有redis，读取 redis
            $activityList = (new self)->getActivityList(['seckill'], $type);
        } else {
            $where = [
                'type' => 'seckill'
            ];
            if ($type == 'ing') {
                $where['starttime'] = ['<', time()];
                $where['endtime'] = ['>', time()];
            } else if ($type == 'nostart') {
                $where['starttime'] = ['>', time()];
            } else if ($type == 'ended') {
                $where['endtime'] = ['<', time()];
            }
        }

        // 获取所有商品 id
        $goodsIds = '';
        foreach ($activityList as $key => $activity) {
            $goodsIds .= ',' . $activity['goods_ids'];
        }

        if ($goodsIds) {
            $goodsIds = trim($goodsIds, ',');
        }

        $goodsList = self::getGoodsListByIds($goodsIds);

        return $goodsList;
    }

    public static function getGoodsListByIds($goodsIds)
    {
        $goodsIdsArray = array_filter(explode(',', $goodsIds));
        $total = count($goodsIdsArray);
        $goods = self::where('status', 'up')
            ->where('deleted_at', null)
            ->whereIn('id', $goodsIdsArray)
            ->get();

        if ($goods) {
            // 处理活动
            foreach ($goods as $key => $g) {
                $data[$key] = self::operActivity($g, $g->skuPrice);
            }
        }

        return [
            'current_page' => 1,
            'last_page' => ceil($total / 10),
            'per_page' => 10,
            'total' => $total,
            'data' => $data ?? [],
        ];
    }

    public static function getGoodsList($params, $is_page = true)
    {
        $type = $params['type'] ?? 'all';
        $order = $params['order'] ?? '';
        $keywords = $params['keywords'] ?? '';
        $goods_ids = $params['goods_ids'] ?? '';
        $category_id = $params['category_id'] ?? '';
        $no_activity = $params['no_activity'] ?? '';
        $delivery_card_id = $params['delivery_card_id'] ?? 0;

        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;

        $query = (new self)
            ->with(['skuPrice'])
            ->where('status', 'up');

        // 只从代客下单的子分类中搜索BOF
        $category_ids = categoryModel::where('pid', 1)
            ->where('status', 'normal')
            ->pluck('id')
            ->toArray();
        $findSqlArr = [];
        foreach ($category_ids as $one_category_id) {
            $findSqlArr[] = ' FIND_IN_SET(' . $one_category_id . ', category_ids) ';
        }
//        $query = $query->where(function($query) use($findSqlArr){
//            $query->whereRaw(implode(' OR ', $findSqlArr));
//        });

        // 只从代客下单的子分类中搜索EOF

        if ($delivery_card_id) {
            $user = \app\service\auth::getUser();
            $member_card = DB::table('member_pickgoods_card')
                ->where('member_id', $user->id)
                ->find($delivery_card_id);
            if (!$member_card) {
                throw new Exception('用户提货卡不存在');
            }
            $card = DB::table('pickgoods_card')->find($member_card->card_id);
            if (!$card) {
                throw new Exception('提货卡不存在');
            }
            $query->whereIn('id', explode(',', $card->goods_ids));
        }

        if (!empty($order)) {
            $order = self::getGoodsListOrder($order);
        } else {
            $order = 'weigh desc';
        }

        if (!empty($keywords)) {
            $query->where(function($query) use ($keywords) {
                $query->where('title', 'like', "%{$keywords}%")
                    ->orWhere('subtitle', 'like', "%{$keywords}%");
            });
        }

        if (!empty($goods_ids)) {
            $order_raw = 'field(id, ' . $goods_ids . ')';
            $query->whereIn('id', explode(',', $goods_ids));
        }

        if (!empty($category_id)) {
            $category_ids = categoryModel::getCategoryIds($category_id);
            $query->where(function ($query) use ($category_ids) {
                foreach ($category_ids as $category_id) {
                    $query->orWhereRaw("find_in_set($category_id, category_ids)");
                }
            });

        }

        // // 过滤有活动的商品
        // if (!empty($no_activity)) {
        //     $query->whereNotExists(function ($query) use ($where) {
        //         $activityTableName = (new Activity())->getQuery()->getTable();
        //         $goodsTableName = (new self())->getQuery()->getTable();
        //         $query->table($activityTableName)->where("find_in_set(" . $goodsTableName . ".id, goods_ids)")->where('deletetime', 'null');        // 必须手动加上 deletetime = null
        //     });
        // }

        $query->selectRaw('*,(sales + show_sales) as total_sales')->orderByRaw($order_raw ?? $order);
        $total = $query->count();
//        dump($total);exit();

        if ($is_page) {
            $data = $query->offset(($page - 1) * $per_page)->limit($per_page)->get();
        } else {
            $data = $query->get();
        }

        $result = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];

        return $result;
    }

    public static function getGoodsListAllCate($params, $is_page = true)
    {
        $type = $params['type'] ?? 'all';
        $order = $params['order'] ?? '';
        $keywords = $params['keywords'] ?? '';
        $goods_ids = $params['goods_ids'] ?? '';
        $category_id = $params['category_id'] ?? '';
        $no_activity = $params['no_activity'] ?? '';
        $delivery_card_id = $params['delivery_card_id'] ?? 0;

        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;

        $query = (new self)
            ->with(['skuPrice' => function ($query) {
                $query->where('stock', '>', 0);
            }])
            ->where('status', 'up');

        if ($delivery_card_id) {
            $user = \app\service\auth::getUser();
            $member_card = DB::table('member_pickgoods_card')
                ->where('member_id', $user->id)
                ->find($delivery_card_id);
            if (!$member_card) {
                throw new Exception('用户提货卡不存在');
            }
            $card = DB::table('pickgoods_card')->find($member_card->card_id);
            if (!$card) {
                throw new Exception('提货卡不存在');
            }
            $query->whereIn('id', explode(',', $card->goods_ids));
        }

        if (!empty($order)) {
            $order = self::getGoodsListOrder($order);
        } else {
            $order = 'weigh desc';
        }

        if (!empty($keywords)) {
            $query->where(function($query) use ($keywords) {
                $query->where('title', 'like', "%{$keywords}%")
                    ->orWhere('subtitle', 'like', "%{$keywords}%");
            });
        }

        if (!empty($goods_ids)) {
            $order_raw = 'field(id, ' . $goods_ids . ')';
            $query->whereIn('id', explode(',', $goods_ids));
        }

        if (!empty($category_id)) {
            $category_ids = categoryModel::getCategoryIds($category_id);
            $query->where(function ($query) use ($category_ids) {
                foreach ($category_ids as $category_id) {
                    $query->orWhereRaw("find_in_set($category_id, category_ids)");
                }
            });
        }

        $query->selectRaw('*,(sales + show_sales) as total_sales')->orderByRaw($order_raw ?? $order);
        $total = $query->count();
        if ($is_page) {
            $data = $query->offset(($page - 1) * $per_page)->limit($per_page)->get();
        } else {
            $data = $query->get();
        }

        $result = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];

        return $result;
    }

    public static function getGoodsDetail($id)
    {
        $userinfo = \app\service\auth::userinfo();
        $detail = (new self)->where('id', '=', $id)->first();
        if (!$detail || $detail->status === 'down') {
            ret(300, '商品不存在或已下架');
        }
        $detail = $detail->toArray();
        if ($userinfo) {
            $detail['favorite'] = memberfavoriteModel::where('goods_id', $id)->where('member_id', $userinfo['id'])->first();
        }

        $service_ids = $detail['service_ids'];
        $serviceData = [];
        if (!empty($service_ids)) {
            $serviceArray = explode(',', $service_ids);
            $serviceData = goodsserviceModel::whereIn('id', $serviceArray)->get();
        }
        $detail['service'] = $serviceData;

        $sku = goodsskuModel::where([
            ['goods_id', '=', $id],
            ['pid', '=', 0],
        ])->get()->toArray();
        foreach ($sku as $s => $k) {
            $sku[$s]['content'] = goodsskuModel::where([
                ['goods_id', '=', $id],
                ['pid', '=', $k['id']],
            ])->get();
        }
        $detail['sku'] = $sku;
        $detail['sku_price'] = goodsskupriceModel::where([
            ['goods_id', '=', $id],
            ['status', '=', 'up'],
        ])->get();

        $detail['coupons'] = couponsModel::whereRaw('find_in_set(' . $id . ',goods_ids)')
            ->orWhere('goods_ids', 0)
            ->get();

        // 处理活动规格
        // $detail = self::operActivity($detail, $detail->sku_price);

        return $detail;
    }

    private static function getGoodsListOrder($orderStr)
    {
        $order = 'weigh desc';
        $orderList = json_decode(htmlspecialchars_decode($orderStr), true);
        extract($orderList);
        if (isset($defaultOrder) && $defaultOrder === 1) {
            $order = 'weigh desc';
        }
        if (isset($priceOrder) && $priceOrder === 1) {
            $order = "convert(`price`, DECIMAL(10, 2)) asc";
        } elseif (isset($priceOrder) && $priceOrder === 2) {
            $order = "convert(`price`, DECIMAL(10, 2)) desc";
        }
        if (isset($salesOrder) && $salesOrder === 1) {
            $order = 'total_sales desc';
        }
        if (isset($newProdcutOrder) && $newProdcutOrder === 1) {
            $order = 'id desc';
        }
        return $order;

    }

    public function dianpu()
    {
        return $this->belongsTo(dianpuModel::class, 'dianpu_id', 'id');
    }
}

